from musicmanager.models import Music,MusicInfo
from xiamisearch import search
import simplejson
from musicmanager.tcommonfunc import getSingerNameByMusicId

def getXiamiMusicId(mid):
    m = Music.objects.get(pk = mid)
    
    if MusicInfo.objects.filter(music__id__exact=mid).count() == 0:
        mi = MusicInfo()
        mi.music = m
        mi.info = "{}"
        mi.save()

    mi = MusicInfo.objects.filter(music__id__exact=mid)[0]
    info = simplejson.loads(mi.info)
    if info.has_key("xiamisongid") == False:
        tracks = search(m.name.encode("utf-8")+" "+getSingerNameByMusicId(m.id).encode("utf-8"))['tracks']
        if len(tracks) == 0:
            tracks = search(m.name.encode("utf-8"))['tracks']
        info["xiamisongid"] = tracks[0]["songid"]
        mi.info = simplejson.dumps(info)
        mi.save()
        
    return info["xiamisongid"]
        
